package com.shujia.mapredue;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Demo9MapJoin {

    public static class MapJoinMap extends Mapper<LongWritable, Text, Text, NullWritable> {

        //使用hashmap保存学生信息，医学好作为key, 以学生信息作为value
        HashMap<String, String> students = new HashMap<String, String>();

        /**
         * setup： 每一个maptask执行一次
         * <p>
         * setup :在map执行之前执行
         */
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {

            //在大表关联小表的时候，由于小表比较小，可以直接放在内存中，
            //可以在每一个maptask中将小表加载到内存中，在map端实现join

            //获取文件系统的对象
            FileSystem fileSystem = FileSystem.get(context.getConfiguration());

            //学生表比较小，可以将学生表加载到内存
            FSDataInputStream fsDataInputStream = fileSystem.open(new Path("/data/student/students.txt"));

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fsDataInputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String id = line.split(",")[0];

                students.put(id, line);
            }

        }

        /**
         * map ： 每一条数据执行一次，
         */
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();

            //分数表中的学号
            String id = line.split(",")[0];

            //通过学号直接冲集合中获取学生的信息
            String student = students.get(id);


            //将数据保存到hdfs
            context.write(new Text(line + "," + student), NullWritable.get());

        }
    }


    public static void main(String[] args) throws Exception {

        Job job = Job.getInstance();

        //mapjoin不需要reduce
        job.setNumReduceTasks(0);

        job.setJarByClass(Demo9MapJoin.class);

        job.setJobName("mapJoin");

        job.setMapperClass(MapJoinMap.class);


        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);


        FileInputFormat.addInputPath(job, new Path("/data/score"));


        FileOutputFormat.setOutputPath(job, new Path("/data/mapjoin"));


        job.waitForCompletion(true);

    }
}
